function updatePrivilage(newPri) {
    var arr = _multiSelection.getSelectionGroupDataArr();
    var $lilist = _multiSelection.getLiSelection();
    var postParam = {
        folderIds:$.cutArrayProp(arr.dirs,"id"),
        fileIds:$.cutArrayProp(arr.files,"id"),
        newPrivilage:newPri
    };

    var successCb = function () {
        //不刷新版 更新js cache，js relation cache，update ui
        //update cache
        // _dirManager.getTheseAndAllChildrenDirIds($.cutArrayProp(arr.dirs,"id"));
        var affectedDirArr =  _dirManager.getAffectedChildrenDirFileBySelectionDataArr(arr);

        console.log("affectedDirArr:");
        console.log(affectedDirArr);
        affectedDirArr.dirIds.map(function (id) {
            var dt = _dataManager.getDirData(id);
            dt.privilege = newPri;
        });
        affectedDirArr.fileIds.map(function (id) {
            var dt = _dataManager.getFileData(null,id);
            dt.privilege = newPri;
        });

        //refresh ui
        _multiSelection.refreshLiList($lilist);

        //刷新版
        // clearAndRefreshCurrentPage();
    }

    successCb();

    //XHR
    $.ajax({
        url: basePath + "/course/thirdStep/dir/updatePrivilage",
        data: postParam,
        type:"post",
        async: true,
        success: function (json) {
            if (isRequestSuccess(json)) {
            }
        }
    });

}

//decorator 用于通用文件菜单的菜单条目样式
var contextMenuConfig = {
    "getKeyByText":function (str) {
        for(var k in contextMenuConfig){
            var dataOne = contextMenuConfig[k];
            if(typeof dataOne === 'object'){
                if(dataOne.text==str){
                    return k;
                }
            }
        }
    },
    "privilage":{
        text: zLocale.database_jiaoshikejian,
        cls: 'teachervisible_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            // console.log(e);

            // console.log(context.target);
            // console.log(context.target.src);

            //
            updatePrivilage(1);
        }
    },
    "privilageGlobal":{
        text: zLocale.database_quanbukejian,
        cls: 'globalvisible_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            // console.log(e);
            //
            // console.log(context.target);
            // console.log(context.target.src);

            updatePrivilage(0);
        }
    },
    "rename":{
        text: zLocale.database_chongmingming,
        cls: 'rename_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            e.stopPropagation();

            context.closeAll();

            console.log(e);
            // deletePost($(context.target));
            var findP = $(context.target).parents("li").find("p.editdataname-p");
            console.log(findP);
            findP.click();

            // changeToInputStatus(findP);
        }
    },
    "download":{
        text: zLocale.database_xiazai,
        cls: 'download_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log('action download');

            var arr = _multiSelection.getSelectionDataArrWithType(true);
            var ts = 0;
            var ts_inc = 200;
            console.log("~~~~~~~~~~~~~~~~~~~~"+arr.length);
            // alert("~~~~~~~~~~~~~~~~~~~~"+arr.length);
            arr.map(function (dt) {
                console.log(dt);
                // if(dt.url) {
                    setTimeout(function () {
                        console.log('open download...');
                        // console.log(dt);
                        // window.open(dt.url);
                        if(dt.type == "pic"){
                            _filePreviewer.downloadPic(dt.url);
                        }
                        else {
                            window.open(dt.url,_filePreviewer.getExplorerOpenType());
                        }
                    },ts);
                    //
                    ts+=ts_inc;

                    // pic.document.execCommand("SaveAs");
                    // $.ajax({
                    //     url:dt.url
                    // });
                // }
            });

        }
    },
    "cut":{
        text: zLocale.database_jianqie,
        cls: 'cut_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log('action cut');

            //剪切的目录
            _dirManager.recordDirPath();
            // console.log(_dirManager._last_cut_dir_path);

            //clear cut object first
            //clear cut object in js data
            _multiSelection.clearAllObjectUIAndProp("cutting","_cutting",true);
            //clear copy object first
            //clear copy object in js data
            _multiSelection.clearAllObjectUIAndProp("copying","_copying",true);

            //update UI
            var $li_list = _multiSelection.updateLiSelectionUI("cutting");

            //update js data
            _multiSelection.updateObjectProp($li_list,"_cutting",true);

        }
    },
    "copy":{
        text: 'Copy',
        cls: '',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log('action copy');

            //clear cut object first
            //clear cut object in js data
            _multiSelection.clearAllObjectUIAndProp("cutting","_cutting",true);
            //clear copy object first
            //clear copy object in js data
            _multiSelection.clearAllObjectUIAndProp("copying","_copying",true);

            //update UI
            var $li_list = _multiSelection.updateLiSelectionUI("copying");

            //update js data
            _multiSelection.updateObjectProp($li_list,"_copying",true);

        }
    },
    "createFolder":{
        text: zLocale.database_menu_create_folder,
        cls: 'createfolder_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log('action createFile');

            $(".greatefolder-div").click();
        }
    },
    "createFile":{
        text: 'Create File',
        cls: '',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log('action createFile');

            // $(".addico").click();
            // $("#uploadFileBtn").click();
            // $("#uploadFileBtnGen input").click()
            $("#uploadFileBtn input").click()
        }
    },
    "paste":{
        text: zLocale.database_zhantie,
        cls: 'paste_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log('action paste');

            //判断粘贴的目录是否合法
            var checkLegalPastePathRs = _dirManager.checkLegalPastePath();
            console.log('checkLegalPastePathRs:'+checkLegalPastePathRs);

            if(checkLegalPastePathRs==0){
                console.log('paste legal path.~~~');

                pasteToDir("cutting","_cutting",_dirManager.currentDirId());

            } else if (checkLegalPastePathRs==1) {
                _multiSelection.clearAllObjectUIAndProp("cutting","_cutting",true);
                _multiSelection.clearAllObjectUIAndProp("copying","_copying",true);
            } else if (checkLegalPastePathRs==2) {
                _alertManager.alertDirPathIllegal();
            }

        }
    },
    "deleter":{
        text: zLocale.database_shanchu,
        cls: 'delete_ico',
        href: '#',
        action:function (e) {
            e.preventDefault();
            console.log(e);
            // console.log(context.target);
            // console.log(context.target.src);
            // deletePost($(context.target));

            var $lilist = _multiSelection.getLiSelection();
            console.log($lilist);

            deleteMultiPost($lilist);
        },
        decorator:function ($li) {
            // console.log($li);
            // $li.find("a").css({"color":"red"});
            return $li;
        }
    },
};
var commonFileAndDirOperFilterArr = ['rename','privilage','privilageGlobal'];//在多选模式中移除选项
var commonFileAndDirDecorator = function ($container,iter) {
    //initial
    iter(function ($li, data) {
        $li.show();
        $li.removeClass("nocursorlist").addClass("cursorlist");

    });

    //多选模式中
    //single only->hide
    if(_multiSelection.isMultiSelected()){
        iter(function ($li, data) {
            // console.log(arguments);
            var k = contextMenuConfig.getKeyByText(data.text);

            //blacklist->hide
            //在多选模式中移除选项
            if($.inArray(k,commonFileAndDirOperFilterArr) >= 0 ){
                $li.hide();
            }
        });
    }

    //多选模式中
    //intersection only
    //TODO 理论上求数组交集
    if(_multiSelection.isMultiSelected()){
        var dirCount=0;
        var fileCount=0;
        var videoCount=0;
        var arr = _multiSelection.getLiSelection();
        arr.each(function (idx,e) {
            if($(e).data("type") == 'dir'){
                dirCount++;
            } else if($(e).data("type") == 'video'){
                videoCount++;
            }else {
                fileCount++;
            }
        });

        //文件夹和视频不支持下载
        if(!(dirCount == 0 && videoCount == 0)){
            var rm = ["download"];
            iter(function ($li, data) {
                var k = contextMenuConfig.getKeyByText(data.text);
                //blacklist->hide
                if($.inArray(k,rm) >= 0 ){
                    $li.hide();
                }
            });
        }

    }

    //privilage <-> privilageGlobal
    var arr = _multiSelection.getSelectionDataArr();
    var liarr = _multiSelection.getLiSelection();
    var curDirDt = _dirManager.currentDirData();
    var parentPri = _dirManager.currentDirPri();
    var curDirDeep = _dirManager.currentDirDeep();

    if (arr.length == 1) {
        var dt = arr[0];
        var lidt = liarr.eq(0);

        console.log(dt);
        //仅教师
        if(parentPri == 1){
            iter(function ($li, data) {
                var k = contextMenuConfig.getKeyByText(data.text);
                if(k == 'privilage' || k == 'privilageGlobal'){
                    $li.removeClass("cursorlist").addClass("nocursorlist");
                }
            });
        } else {
            //全部可见

        }

        //root下的 Course Videos 不可设置权限
        if(curDirDeep == 1 && lidt.data("type") == "dir" && dt.name == "Course Videos"){
            iter(function ($li, data) {
                var k = contextMenuConfig.getKeyByText(data.text);
                if(k == 'privilage'){
                    $li.hide();
                }
                if(k == 'privilageGlobal'){
                    $li.hide();
                }
            });
        }
        //其它情况
        else {

            //toggle 菜单条目
            iter(function ($li, data) {
                var k = contextMenuConfig.getKeyByText(data.text);
                console.log(k);

                if(dt.privilege){
                    if(k == 'privilage'){
                        $li.hide();
                    }

                    if(k == 'privilageGlobal'){
                        $li.show();
                    }
                } else {
                    if(k == 'privilage'){
                        $li.show();
                    }

                    if(k == 'privilageGlobal'){
                        $li.hide();
                    }
                }
            });
        }

    }

    return true;
}
var _t_getIconX = function ($con) {
    return $con.offset().left+$con.width()+10;
}

var commonFileAndDirPositionUp = function (mouseX,mouseY,$menuCom,$target) {
    var autoH = $menuCom.height() + 12;
    var $con = $target.closest(".databasecontetdiv");

    return {
        top: mouseY - 20 - autoH,
        left: _t_getIconX($con)
    };
}
var commonFileAndDirPositionNormal = function (mouseX,mouseY,$menuCom,$target) {
    var $con = $target.closest(".databasecontetdiv");
    // console.log($con);
    // console.log($con.offset());
    // console.log($con.width());
    // console.log($con.outerWidth());
    // console.log($con.outerWidth(true));

    var newVar = {
        top: $con.offset().top,
        // left: e.pageX - 13
        left: _t_getIconX($con)
    };
    console.log(newVar);
    return newVar;
}

var commonFileAndDirPositionConfig = {
    // positionNormal:commonFileAndDirPositionNormal,
    // positionUp:commonFileAndDirPositionUp
}

//各种图标类型的菜单操作内容
var _commonDirMenuMap = [contextMenuConfig.privilage,contextMenuConfig.privilageGlobal,contextMenuConfig.rename,contextMenuConfig.cut,contextMenuConfig.deleter];//不能下载文件夹
var _commonFileMenuMap = [contextMenuConfig.rename,contextMenuConfig.download,contextMenuConfig.cut,contextMenuConfig.deleter];//不能设置可见度
var _videoMenuMap = [contextMenuConfig.rename,contextMenuConfig.cut,contextMenuConfig.deleter];//不能设置可见度 不能下载
var _containerMenuMap = [contextMenuConfig.paste,contextMenuConfig.createFolder];//,contextMenuConfig.createFile


var _config = {isCtrlMultiSelectionEnabled:true,hasPrevDir:true,enableAnimate:true};//一些配置项 一般不用变
var _data = {};//ajax查到的数据  都缓存到里面
var _meta = {
    contentId: "fileContent",//所有文件的容器div id
    currentPathArr: [],//breadcrumb 路径记录
    dirView: 1,//1:显示文件夹结构 2:不显示文件夹,所有类型直接平铺到root
    modeView: 2,//1:列表 2:平铺
    tabView: 1,//1:All 2:picture 3:video 4:files
    tabType: {
        "1": ["*"],
        "2": ["pic"],
        "3": ["video"],
        "4": ["word", "excel", "pdf", "zip"]
    },
    //生成后如 docx : file-word
    //suffixToType+typeToClass=suffixToClass
    suffixToClass: {
//            should init
    },

    //决定后缀属于哪种类型，同时用来限制上传文件类型
    suffixToType: {
        "doc": "word",
        "docx": "word",
        "xls": "excel",
        "xlsx": "excel",
        "pdf": "pdf",
        "ppt": "ppt",
        "pptx": "ppt",
        "zip": "zip",
        "rar": "zip",
        "mp4": "video",
        "jpeg": "pic",
        "jpg": "pic",
        "png": "pic",
        "gif": "pic",
    },
    //决定类型使用哪种class icon
    typeToClass: {
        "word": "file-word",
        "excel": "file-excel",
        "pdf": "file-pdf",
        "ppt": "file-ppt",
        "zip": "file-zip",
        "video": "video",
        "pic": "pic"
    },

    //控制菜单选项
    //decorator 用于精确控制各种文件菜单的菜单条目
    // 目前用来控制是否显示
    contextMenuMap: {
        "mark-file-word":{
            "map":_commonFileMenuMap,//菜单有哪些操作的配置项
            "decorator":commonFileAndDirDecorator,//规定哪些条目不显示，或者需要修饰后显示  比如名称为Course Videos的文件夹不能操作权限
            "positionConfig":commonFileAndDirPositionConfig//配置菜单出现位置，目前已无用
        },
        "mark-file-excel":{
            "map":_commonFileMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-file-pdf":{
            "map":_commonFileMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-file-ppt":{
            "map":_commonFileMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-file-zip":{
            "map":_commonFileMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-video":{
            "map":_videoMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-pic":{
            "map":_commonFileMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-file mark-common":{
            "map":_commonDirMenuMap,
            "decorator":commonFileAndDirDecorator,
            "positionConfig":commonFileAndDirPositionConfig
        },
        "mark-file mark-prev":{
            "map":[],
            "decorator":function ($container,iter) {
                return false;
            }
        },
        "mainContainer":{
            "map":_containerMenuMap,
            "decorator":function ($container,iter) {

                iter(function ($li, data) {
                    // console.log(arguments);
                    var k = contextMenuConfig.getKeyByText(data.text);

                    if(k=='paste'){
                        if(_multiSelection.hasCutorCopy()){
                            // $li.find("span").removeAttr("disabled");
                            $li.removeClass("nocursorlist");
                            $li.addClass("cursorlist");
                        } else {
                            // $li.addClass("disabled");
                            // $li.find("a").attr("disabled","true");
                            $li.removeClass("cursorlist");
                            $li.addClass("nocursorlist");

                        }
                    }

                });

                return true;
            }
        }
    },
    "iconAction":{
        "video":function (id,data,$li) {
            var infId = data.interfaceDataId;
            console.log('click video');
            console.log(data);
            console.log(infId);

            //若转码成功&有videoId
            if(data.videoSize && !isEmpty(infId)) {
                if(!isEmpty(infId)){
                    videoShow();
                    videoPlayer(infId,"");
                    $("#videoPlayer").show();
                }
            }
        },
        "pic":function (id,data,$li) {
            // layer.open({
            //     type: 1,
            //     title: false,
            //     // closeBtn: 0,
            //     closeBtn: 1,
            //     // area: '516px',
            //     shade: [0.5, '#393D49'],
            //     area: ['auto','auto'],
            //     skin: 'layui-layer-nobg', //没有背景色
            //     shadeClose: true,
            //     content: "<img src='"+data.url+"' />"
            // });
            // $li.attr("src",data.url);
            // $li.tmImgbox({
            // });

            $.tmImgbox(data.id);
        },
        "word":function (id,data,$li) {
            _previewDocFile.apply(_previewDocFile,arguments);
        },
        "excel":function (id,data,$li) {
            _previewDocFile.apply(_previewDocFile,arguments);
        },
        "pdf":function (id,data,$li) {
            _previewDocFile.apply(_previewDocFile,arguments);
        },
        "ppt":function (id,data,$li) {
            _previewDocFile.apply(_previewDocFile,arguments);
        },
        "zip":function (id,data,$li) {
            // _previewDocFile.apply(_previewDocFile,arguments);
        }
    }
};

function _previewDocFile(id,data,$li) {
    console.log(arguments);
    // data.url;
    // data.interfaceDataId;

    // //iframe层-多媒体

    _filePreviewer.preViewFile(id,data.interfaceDataId,data);

}

//init suffixToClass
(function () {
    for (var su in _meta.suffixToType) {
        var tp = _meta.suffixToType[su];
        _meta.suffixToClass[su] = nullToEmptyString(_meta.typeToClass[tp]);
    }
})();


function DivBuilder() {
}

DivBuilder.prototype = {
    createBase: function () {
        var $li = $("#baseFileDiv").clone();
        $li.removeClass("hidden");
        $li.removeAttr("id");
        return $li;
    },
    createBySuffix: function (suffix) {
        var $base = this.createBase();
        this._attr_type_cls($base, nullToEmptyString(_meta.suffixToClass[suffix]));
        return $base;
    },
    createDir: function () {
        var $base = this.createBase();
        this._attr_type_cls($base, "file common");
        return $base;
//            return this.createBySuffix("dir");
    },
    createPrevDir: function () {
        var $base = this.createBase();
        this._attr_type_cls($base, "file prev");
        return $base;
//            return this.createBySuffix("prevdir");
    },
    _attr_type_cls: function ($base, cls) {
        $base.find(".icotop-span > span:eq(0)").addClass(cls);

       var clses =  splitBySpace(cls);
        for(var i=0;i<clses.length;i++) {
            $base.find(".databasecontetdiv").addClass("mark-"+clses[i]);
        }

        return $base;
    },
    _attr_name: function ($base, name) {
        $base.find("p.editdataname-p").text(name);
        $base.find("p.editdataname-p").attr("title", name);
        return $base;
    }
}
function DirManager() {
}
DirManager.prototype = {
    _last_unique_check:true,
    _last_cut_dir_path:[],
    currentDirId: function () {
        return _meta.currentPathArr[_meta.currentPathArr.length - 1];
    },
    currentDirDeep: function () {
        return _meta.currentPathArr.length;
    },
    currentDirPri: function () {
        var parentPri = this.currentDirData().privilege || 0;
        return parentPri;
    },
    currentDirData: function () {
        var dirId = this.currentDirId();
        return _dataManager.getDirData(dirId);
    },
    recordDirPath: function () {
        this._last_cut_dir_path.removeAll();
        Array.prototype.push.apply(this._last_cut_dir_path,_meta.currentPathArr);
    },
    lastRecordedDirPath: function () {
        return this._last_cut_dir_path;
    },
    checkLegalPastePath: function () {
        var cutPath = this.lastRecordedDirPath();//#1
        var cutDataArr = _multiSelection.getCuttingGroupData();//#2
        var currentPath = _meta.currentPathArr;//#3

        //check src==dest
        var allEquals = true;
        for (var i = 0; i <  cutDataArr.dirs.length; i++) {
            var obj =  cutDataArr.dirs[i];
            var filePath = _dirManager.getDirPath(obj.id,true);
            if (!$.arrayEqual(filePath,currentPath)) {
                allEquals = false;
                break;
            }
        }
        for (var i = 0; i <  cutDataArr.files.length; i++) {
            var obj =  cutDataArr.files[i];
            var filePath = _dirManager.getDirPath(obj.id,false);
            if (!allEquals || !$.arrayEqual(filePath,currentPath)) {
                allEquals = false;
                break;
            }
        }
        if (allEquals){
            return 1;
        }

        //check illegal
        for (var i = 0; i <  cutDataArr.dirs.length; i++) {
            var obj = cutDataArr.dirs[i];
            if ($.inArray(obj.id,currentPath) >=0) {
                return 2;
            }
        }

        // if ($.arrayEqual(cutPath,currentPath)) {
        //     console.log('dest == src');
        //     return 1;
        // }
        //
        // //check dest is children of src
        // else {
        //     var illegal = false;
        //     cutDataArr.dirs.map(function (dt) {
        //         if ($.inArray(dt.id,currentPath) >=0) {
        //             illegal = true;
        //         }
        //     });
        //     if (illegal) {
        //         console.log('dest is children of src');
        //
        //         return 2;
        //     }
        // }

        //check dir name unique

        return 0;
    },
    currentChildrenDirIds: function () {
        var curDirId = this.currentDirId();
        return this.getChildrenDirIds(curDirId);
    },
    getThisAndAllChildrenDirIds: function (dirId) {
        var ret = [];
        _painter.pushToArr(ret, dirId);

        var childrenDirIds = this.getChildrenDirIds(dirId);

        for (var i = 0; i < childrenDirIds.length; i++) {
            var childrenDirId = childrenDirIds[i];

            _painter.pushToArr(ret,  this.getThisAndAllChildrenDirIds(childrenDirId));
        }

        return ret;
    },
    getTheseAndAllChildrenDirIds: function (dirIds) {
        var ret = [];
        dirIds.map(function (id) {
            _painter.pushToArr(ret, _dirManager.getThisAndAllChildrenDirIds(id));
        });
        return ret;
    },
    getAffectedChildrenDirFileBySelectionDataArr: function (arr) {
        var affectedDirArr =  _dirManager.getTheseAndAllChildrenDirAndFileIds($.cutArrayProp(arr.dirs,"id"),$.cutArrayProp(arr.files,"id"));
        return affectedDirArr;
    },
    getTheseAndAllChildrenDirAndFileIds: function (pdirIds,pfileIds) {
        var ret = {dirIds:[],fileIds:[]};
        ret.dirIds=this.getTheseAndAllChildrenDirIds(pdirIds);

        if(pfileIds){
            _painter.pushToArr(ret.fileIds, pfileIds);
        }

        ret.dirIds.map(function (dirId) {
            _painter.pushToArr(ret.fileIds,  _dataManager.getFileIdsForDir(dirId));
        });
        return ret;
    },
    getChildrenDirIds: function (dirId) {
        return nullToEmptyArray(_data.dirMapping[dirId]);
    },
    getCurrentDirStreamDataArr: function () {
        var ret = [];
        _meta.currentPathArr.map(function (dirId) {
            var dirData = nullToEmptyObject(_data.dirs[dirId]);
            ret.push({
                name:dirData.name,
                id:dirId
            });
        });
        ret[0].name="Home";
        return ret;
    },
    currentDirFiles: function () {
        var curDirId = this.currentDirId();
        return _dataManager.getFilesArrForDir(curDirId);
    },
    enterDirectory: function (dirId) {
        _meta.currentPathArr.push(dirId);
        _painter.paint();
    },
    breadDirectory: function (dirId) {
        var idx = $.inArray(dirId,_meta.currentPathArr);
        // console.log(idx);
        if(idx>=0 && idx<_meta.currentPathArr.length-1){
            // console.log("arr:"+_meta.currentPathArr);
            var s = _meta.currentPathArr.splice(idx+1);
            // console.log("s:"+s);
            // console.log("arr:"+_meta.currentPathArr);
            _painter.paint();
        }
    },
    popDirectory: function () {
        // _meta.currentPathArr.pop();
        // _painter.paint();
        // console.log(_meta.currentPathArr.length - 2);
        // console.log(_meta.currentPathArr[_meta.currentPathArr.length - 2]);
        this.breadDirectory(_meta.currentPathArr[_meta.currentPathArr.length - 2]);
    },
    isRootDir: function () {
        return _meta.currentPathArr.length == 1;
    },
    checkUnique: function (dirName,parentDirId) {
        var ret = true;
        if(parentDirId && dirName){
            var cdDirIds = this.getChildrenDirIds(parentDirId);
            for (var i = 0; i < cdDirIds.length; i++) {
                var childrenDirId = cdDirIds[i];

                var cdDir = _data.dirs[childrenDirId];
                if(cdDir && cdDir.name == dirName){
                    ret = false;
                    break;
                }
            }
        }
        this._last_unique_check = ret;
        return ret;
    },
    dirContainsTabViewData:function (dirId) {
        var curTab = _meta.tabView;
        var tabTypesArr = _meta.tabType[curTab+""];
        if($.inArray("*",tabTypesArr) >= 0){
            return true;//该目录恒显示
        }

        console.log("search direct children...");
        //当前文件夹下文件
        var dataArr = _dataManager.getFilesArrForDir(dirId);
        for(var i =0;i< dataArr.length;i++) {
            var fileData = dataArr[i];

            if(_fileManager.tabFilter(fileData)){
                return true;//目录需要显示
            }
        }

        console.log("search all children...");
        //递归该文件夹下文件夹
        var childrenDirIds =  _data.dirMapping[dirId] || [];
        for(var i = 0;i< childrenDirIds.length;i++) {
            var childrenDirId = childrenDirIds[i];
            var child = _dirManager.dirContainsTabViewData(childrenDirId);
            if(child) {
                return  true;//目录需要显示
            }
        }

        return false;
    },
    getDirPath:function (id,isDir,startDirId) {
        var ret = [];
        var r_startDirId = startDirId;
        if(!startDirId){
            r_startDirId = _data.rootDirId;
        }
        var childrenDirArr;
        if(isDir) {
            childrenDirArr = _data.dirMapping[r_startDirId] || [];
            if($.inArray(id,childrenDirArr) >=0 ){
                ret.push(r_startDirId);
                return ret;
            }
        } else {
            var fileIdArr = _dataManager.getFileIdsForDir(r_startDirId);
            if($.inArray(id,fileIdArr) >=0 ){
                ret.push(r_startDirId);
                return ret;
            }

            childrenDirArr = _data.dirMapping[r_startDirId] || [];
        }

        for (var i = 0; i < childrenDirArr.length; i++) {
            var cdDirId = childrenDirArr[i];
            var cdArr = _dirManager.getDirPath(id,isDir,cdDirId);
            if(cdArr.length > 0){
                ret.push(r_startDirId);
                _painter.pushToArr(ret,cdArr);
                return ret;
            }
        }
        return ret;
    }
}

function Painter() {
}
Painter.prototype = {
    _attach_queue:[],
    _ani_queue_int:null,
    paint: function (forceInstant) {
        this.destroyQueueAnimate();//删除文件绘制动画

        this.resetMark();//防止编辑文件或文件夹命名失效

        closeAllContextMenu();//关闭所有右键菜单

        this.clear();//清空html

        this.paintBreadCrumb();

        var itemArr = [];
        this.pushToArr(itemArr,this.createPrevDir());

        this.pushToArr(itemArr,this.createChildrenDir());

        this.pushToArr(itemArr,this.createCurrentDirFiles());

        // $(".databasecontet-div .nano").nanoScroller();
        _pageHandler.processItems(itemArr,forceInstant);

        this.repaintScroll();

        this.setAllowUploadSuffix();
    },
    setAllowUploadSuffix: function () {
        var curTab = _meta.tabView;
        //all || files
        if(curTab==1 ){
            //支持全部
            // $("input:file[name='qqfile']").removeAttr("accept");

            //支持部分
            var str = "";
            $.mapKeys(_meta.suffixToType).map(function (suffix) {
                        str = str + "." + suffix + ",";
            });
            $("input:file[name='qqfile']").attr("accept",str);
        }
        else if(curTab==4){
            //支持部分
            var str = "";
            $.mapKeys(_meta.suffixToType).map(function (suffix) {
                var tp = _meta.suffixToType[suffix];

                // console.log("!!!!"+_meta.tabType["2"]);
                // console.log(_meta.tabType["3"]);
                if($.inArray(tp,_meta.tabType["2"])>=0 || $.inArray(tp,_meta.tabType["3"])>=0 ){
                    return;
                }

                str = str + "." + suffix + ",";
            });
            $("input:file[name='qqfile']").attr("accept",str);
        }
        else {
            var str = "";
            var types = _meta.tabType[curTab+""];
            // console.log("!!!!!!!!!!!");
            // console.log(types);
            types.map(function (tp) {
                for(var suffix in  _meta.suffixToType) {
                    if(_meta.suffixToType[suffix] == tp) {
                        str = str + "." + suffix + ",";
                        // str = str + "image/" + suffix + ",";
                    }
                }
            });
            $("input:file[name='qqfile']").attr("accept",str);
            // $("input:file[name='qqfile']").attr("accept","image/gif,image/jpeg,image/jpg,image/png,image/svg,image/bmps");
        }
    },
    repaintScroll: function () {
        $(".databasecontet-div .nano").nanoScroller({destroy:true});
        $(".databasecontet-div .nano").nanoScroller();
    },
    paintBreadCrumb: function () {
        if(_meta.dirView == 1){
            var arr = _dirManager.getCurrentDirStreamDataArr();
            var $con = $("<ul></ul>");

            var i = 0;
            arr.map(function (e) {
                var $one = $("<li></li>");
                $one.text(e.name);
                $one.data("_data",e);//store data

                $one.click(function () {
                    _dirManager.breadDirectory($(this).data("_data").id);
                });

                $con.append($one);
                // $con.append("  ");

                if(i<arr.length-1){
                    $one.css("cursor","pointer");

                    $con.append("<li><span class=\"arrow\"></span></li>");
                }

                i++;
            });

            $(".breadCrumb").append($con);
        }
    },
    pushToArr: function (arr,obj) {
        if(obj){
            if (obj instanceof Array) {
                for (var i = 0; i < obj.length; i++) {
                    arr.push(obj[i]);
                }
            } else {
                arr.push(obj);
            }
        }
    },
    clear: function () {
        $(getContentContainer()).empty();

        //bread
        $(".breadCrumb").empty();
    },
    resetMark: function () {
        _dirManager.checkUnique();
        _fileManager.checkUnique();
    },
    createCurrentDirFiles: function () {

        var curDirId = _dirManager.currentDirId();
       var files ;
        if(_meta.dirView == 1){
            files=_dataManager.getFilesArrForDir(curDirId);
        } else if(_meta.dirView == 2){
            files = _dataManager.getFilesArrForDirIncludeChildren(curDirId);
        }

        return this.createDirFiles(files);
    },
    createDirFiles: function (files) {
        var ret = [];

        if (files){
            for (var i = 0; i < files.length; i++) {
                var file = files[i];

                var $li = this.createChildrenFileOne(file);

                if($li){
                    ret.push($li);
                }
            }
        }

        return ret;

    },
    createPrevDir: function () {
        if (_meta.dirView == 1 && !_dirManager.isRootDir() && _config.hasPrevDir) {
            var $li = _factory.createPrevDir();
            _factory._attr_name($li, "..");
            $li.find(".deleteico").remove();
            $li.find(".teachervisibleico").remove();
            return $li;
        }
    },
    createChildrenDir: function () {
        var ret = [];
        if(_meta.dirView == 1){
            var childrenDirIds = _dirManager.currentChildrenDirIds();

            //只显示包含类当前tab类型的子文件夹
            for (var i = 0; i < childrenDirIds.length; i++) {
                var dirId = childrenDirIds[i];
                var dirData = _data.dirs[dirId];

                if (_dirManager.dirContainsTabViewData(dirId)) {
                    var $li = this.createChildrenDirOne(dirData);
                    ret.push($li);
                }
            }
        }

        return ret;
    },
    createChildrenDirOne: function (dirData) {
        var $li = _factory.createDir();

        this.setDirModelDataToUiEle($li,dirData);

        this.setInteractiveUI($li, dirData);

        return $li;
    },
    setDirModelDataToUiEle: function ($li, dirData) {
        _factory._attr_name($li, dirData.name);
        $li.data("id", dirData.id);
        $li.data("type", "dir");

        if(!dirData.privilege){
            $li.find(".teachervisibleico").hide();
        } else {
            $li.find(".teachervisibleico").show();
        }

        return $li;
    },
    setInteractiveUI:function ($li, data) {
        if(data["_cutting"]){
            $li.addClass("cutting");
        }
        if(data["_copying"]){
            $li.addClass("copying");
        }
    },
    getTypeForFileData:function (fileData) {
        var suffix = _fileManager.getSuffix(fileData);
        var tp = _fileManager.getType(suffix);
        return tp;
    },
    resizeImg:function (img,iwidth,iheight){
        var image= img;
        var boxWH = {};
        if(image.width>0 && image.height>0){
            boxWH.width=image.width;
            boxWH.height=image.height;
            if(boxWH.width>iwidth){
                boxWH.height = (boxWH.height*iwidth)/boxWH.width;
                boxWH.width = iwidth;

            }
            if(boxWH.height>iheight){
                boxWH.width = (boxWH.width*iheight)/boxWH.height;;
                boxWH.height = iheight;
            }
        }
        return boxWH;
    },
    createChildrenFileOne: function (fileData) {
        //过滤
       var  file = _fileManager.tabFilter(fileData);

        if (file) {
            var suffix = _fileManager.getSuffix(fileData);
            var $li = _factory.createBySuffix(suffix);
            var tp = this.getTypeForFileData(fileData);

            this.setFileModelDataToUiEle($li,fileData);

            this.setInteractiveUI($li, fileData);

            if(tp=="dir"){

            } else {
                if(tp == "pic"){

                    if(fileData.url){
                        var img = new Image();
                        img.src = fileData.url;
                        // img.draggable=false;

                        // var $img = $("<img />");
                        // $img.attr("src",fileData.url);
                        // console.log(img.height);
                        // console.log(img.width);

                        var sucCb = function (img) {
                            var maxHeight = 108;
                            // console.log(maxHeight);

                            var box = _painter.resizeImg(img,96,96);
                            // console.log('org:'+img.width+","+img.height);
                            // console.log('box:'+box.width+","+box.height);
                            img.width = box.width;
                            img.height = box.height;

                            var offset =( maxHeight-box.height)/2;
                            offset = offset < 0?0:offset;

                            // $(img).hide();
                            $li.find(".pic").css({top:offset+"px"}).append(img);
                            // $(this).parent().css({top:offset+"px"});
                            // $(img).slideDown(300);
                        }

                        console.log('new Image');
                        if(img.complete){
                            // console.log('complete');
                            sucCb(img);
                        } else {
                            img.onload = function () {
                                // console.log('onload');
                                sucCb(this);
                            }
                        }
                        // console.log(img.height);
                        // console.log(img.width);
                    }
                }

                if(tp == "video"){
                    var videoId = fileData.interfaceDataId;

                    var $img = $("<img />");

                    // $span.append($img);

                    //当有时长时——转码成功
                    if(fileData.videoSize) {
                        var $span = $("<span class='playbtn'></span>");
                        // $img.attr("src","http://image.zhihuishu.com/testzhs/able-commons/demo/201612/13f4768b38f7474a840cca625a85f892.png");
                        $img.attr("src",fileData.thumbnailUrl);
                        $li.find(".video").append($span);
                    } else {
                        var $overlay = $("<div class='video-overlay'></div>");
                        var $transcodeTip = $("<span class='video-transcode-tip'>"+zLocale.thirdstep_zhuanmazhong+"...</span>");
                        $li.find(".video").append($overlay);
                        $li.find(".video").append($transcodeTip);

                        $img.attr("src","http://image.zhihuishu.com/zhs_yanfa_150820/ablecommons/demo/201610/d17412cd6a42431ea7e7779c406269f5.jpg");
                    }

                    $li.find(".video").append($img);
                }

            }

            return $li;
        }

        return null;
    },
    setFileModelDataToUiEle: function ($li, fileData) {
        var suffix = _fileManager.getSuffix(fileData);
        var tp = _fileManager.getType(suffix);

        _factory._attr_name($li, getFilePrefixOnly(fileData.name));
        $li.data("id",fileData.id);
        $li.data("type",tp);

        // if(!dirData.privilege){
            $li.find(".teachervisibleico").hide();
        // }


        return $li;
    },
    attach: function ($div) {

        this._attach_queue.push($div);

        this.activateQueueAnimate();
    },
    attachInstant: function ($div) {
        $(getContentContainer()).append($div);

        _painter.repaintScroll();
    },
    activateQueueAnimate:function () {
        if(!this._ani_queue_int){
//                console.log('_ani_queue_int');
            this._ani_queue_int = setInterval(function () {
                var length = _painter._attach_queue.length;
//                    console.log('aaa'+ length);
                if(length>0){
                    var $div = _painter._attach_queue.shift();
                    $div.hide();
                    $(getContentContainer()).append($div);
                    $div.fadeIn("fast",function () {
                    });
                }else {
                    _painter.repaintScroll();

                    _painter.destroyQueueAnimate();
                }
            },20);
        }
    },
    destroyQueueAnimate:function () {
        this._attach_queue = [];
        clearInterval(this._ani_queue_int);
        this._ani_queue_int = null;
    },
    changeTab: function (newTabIndx,newDirIndx) {
        //back to Root
        _meta.currentPathArr = [_meta.currentPathArr[0]];

        _meta.tabView=newTabIndx;
        _meta.dirView=newDirIndx;

        this.paint();
    },
    refreshDir:function (dt,prop) {
        _dataManager.processUpdateDir(dt.id,prop,dt[prop]);
        _painter.setDirModelDataToUiEle(this.getDirLiById(dt.id,true),dt);
    },
    refreshFile:function (dt,prop) {
        _dataManager.processUpdateFile(null,dt.id,prop,dt[prop]);
        _painter.setFileModelDataToUiEle(this.getDirLiById(dt.id,false),dt);
    },
    getDirLiById:function (id,isDir) {
        var ret ;
        $("#fileContent").find("li").each(function (idx, ele) {
            var cid = $(ele).data("id");
            var tp =  $(ele).data("type");
            if(isDir){
                if(tp == "dir" && cid==id){
                    ret = $(ele);
                }
            }else {
                if(cid==id){
                    ret = $(ele);
                }
            }
        })

        return ret;
    }
}
function FileManager() {
}
FileManager.prototype = {
    _last_unique_check:true,
    tabFilter: function (data) {
        var curTab = _meta.tabView;
        var showSu = _meta.tabType["" + curTab];
        var su = this.getSuffix(data);
        var tp = _meta.suffixToType[su];

        //特殊情形，为2,3的补集
        if(curTab == 4) {
            if($.inArray(tp,_meta.tabType["2"]) >=0 || $.inArray(tp,_meta.tabType["3"]) >=0 ){
                return null;
            } else {
                return data;
            }
        }

        //其它情形
        for (var i = 0; i < showSu.length; i++) {
            var eachSu = showSu[i];

            //特殊情形,* = all
            if (eachSu == "*") {
                return data;
            }
            if (eachSu == tp) {
                return data;
            }
        }
        return null;
    },
    getSuffix: function (data) {
        return data.suffix.toLowerCase();
    },
    getType: function (suffix) {
        return  _meta.suffixToType[suffix];
    },
    checkUnique: function (fileName,dirId) {
        var ret = true;

        if(dirId && fileName) {
            var fileDataArr = _data.files[dirId];
            if (fileDataArr) {
                for (var i = 0; i < fileDataArr.length; i++) {
                    var fileData = fileDataArr[i];

                    if (fileData && fileData.name == fileName) {
                        ret = false;
                        break;
                    }
                }
            }
        }

        this._last_unique_check = ret;
        return ret;
    }
}
function DataManager() {
}
DataManager.prototype = {
    getFileIdsForDir:function (dirId) {
        if(_data.files[dirId]){
            return $.cutArrayProp(_data.files[dirId],"id");
        }
        return [];
    },
    getFilesArrForDir:function (dirId) {
        if(!_data.files[dirId]){
            $.ajax({
                url: basePath + "/course/thirdStep/file/map",
                data: {"foldIds": "" + dirId},
                async: false,
                cache:false,
                success: function (json) {
                    if (isRequestSuccess(json)) {
                        var t_files = json.result.files;

                        _data.files[dirId] = t_files[dirId];
                    }
                }
            });
        }

        return nullToEmptyArray(_data.files[dirId]);
    },
    getFilesArrForDirIncludeChildren:function (dirId) {
        var files = [];
        _painter.pushToArr(files,_dataManager.getFilesArrForDir(dirId));

        var childrenDirIds =  _data.dirMapping[dirId] || [];
        for(var i = 0;i< childrenDirIds.length;i++) {
            var childrenDirId = childrenDirIds[i];
            var childArr = _dataManager.getFilesArrForDirIncludeChildren(childrenDirId);

            _painter.pushToArr(files,childArr);
        }

        return files;
    },
    processNewDir:function (data) {
        var id=data.id;
        if(!_data.dirMapping[data.parentId]){
            _data.dirMapping[data.parentId] = [];
        }
        _data.dirMapping[data.parentId].push(id);
        _data.childrenDirIds.push(id);
        _data.dirs[data.id]=data;
    },
    processNewFile:function (data) {
        var id=data.id;
        var folderId=data.folderId;
        if(folderId){
            if(!_data.files[folderId]){
                _data.files[folderId] = [];
            }
            _data.files[folderId].push(data);
        }
    },
    processUpdateDir:function (id,prop,val) {
        if(val == undefined){
            delete  this.getDirData(id)[prop];
        }else {
            this.getDirData(id)[prop]=val;
        }
    },
    processUpdateFile:function (dirId,fileId,prop,val) {
        if(val == undefined){
            delete   this.getFileData(dirId,fileId)[prop];
        }else {
             this.getFileData(dirId,fileId)[prop]=val;
        }
    },
    processUpdateByLi:function ($li,prop,val) {
        var tp = $li.data("type");
        var tid = $li.data("id");
        // console.log(tp);
        // console.log(tid);
        if(tp=='dir'){
            this.processUpdateDir(tid,prop,val);
        }else {
            this.processUpdateFile(null,tid,prop,val);
        }

    },
    processRemoveDir:function (id) {
        if(!_data.dirMapping[id]){
            _data.dirMapping[id] = [];
        }
        var childrenDirs  =_data.dirMapping[id];

        for (var i = 0; i < childrenDirs.length; i++) {
            var childrenDirId = childrenDirs[i];
            this.processRemoveDir(childrenDirId);
        }

        //delete file
        if (_data.files[id]){
            var fileDataArr = _data.files[id];
            for (var i = 0; i < fileDataArr.length; i++) {
                var fileData = fileDataArr[i];
                this.processRemoveFile(fileData.id,id);
            }
        }

        //delete mapping
        for (var dirId in _data.dirMapping) {
            var cdIdArr = _data.dirMapping[dirId];
            cdIdArr.remove(id);
        }
        delete _data.dirMapping[id];

    },
    processRemoveFile:function (fileId,dirId) {
        if (dirId){
            this.removeFileInArr(_data.files[dirId],fileId);
        } else {
            for (var dirId in _data.files) {
                var fileIdArr = _data.files[dirId];
                this.removeFileInArr(fileIdArr,fileId);
            }
        }
    },
    removeFileInArr:function (arr,fileId) {
        if(arr){
            for (var i = 0; i < arr.length; i++) {
                var fileData = arr[i];
                if(fileData.id==fileId){
                    arr.splice(i, 1);
                }
            }
        }
    },
    getDirData:function (id) {
        if(_data.dirs[id]) {
            return _data.dirs[id];
        }
        return {};
    },
    getFileData:function (dirId,fileId) {
        var files = _data.files[dirId];
        if(files) {
            var findOneByProp = $.findOneByProp(files, "id", fileId);
            if(findOneByProp){
                return  findOneByProp;
            }
        }

        for (var i in _data.files) {
            var dirFileDataArr = _data.files[i];
            var findOneByProp = $.findOneByProp(dirFileDataArr, "id", fileId);
            if(findOneByProp){
                return  findOneByProp;
            }
        }

        return {};
    },
    findFileData:function (prop,val) {
        var ret = [];
        for (var i in _data.files) {
            var dirFileDataArr = _data.files[i];
            var multiArr = $.findMultiByProp(dirFileDataArr, prop, val);

            Array.prototype.push.apply(ret, multiArr);
        }
        return ret;
    },
    findDirData:function (prop,val) {
        var ret = [];
        for (var i in _data.dirs) {
            var dirOne = _data.dirs[i];

            if (dirOne && dirOne[prop] == val) {
                ret.push(dirOne);
            }
        }
        return ret;
    },
    getCurrentPictureData:function () {
        var ret = [];
        var arr ;
        if(_meta.dirView == 1){
            arr = _dataManager.getFilesArrForDir(_dirManager.currentDirId());
        } else if(_meta.dirView == 2) {
            arr = _dataManager.getFilesArrForDirIncludeChildren(_dirManager.currentDirId());
        }
        arr.map(function (dt) {
            var tp = _painter.getTypeForFileData(dt);
            if(tp=='pic') {
                ret.push(dt);
            }
        });
        return ret;
    }
}

function PageHandler() {
}
PageHandler.prototype = {
    processItems:function (items,forceInstant) {
        for (var i = 0; i < items.length; i++) {
            var one = items[i];

            this.processNewItem(one,forceInstant);
        }
    },
    processNewItem:function (item,forceInstant) {
        if(item){
            //ie不支持动画
            //config启动才开启动画
            if(_navig.ie || !_config.enableAnimate || forceInstant){
                // console.log('Instant');
                _painter.attachInstant(item);
            }else {
                // console.log('not Instant');
                _painter.attach(item);
            }
        }

    },
    processDeleteItem:function (item) {
        if(item) {
            item.fadeOut("fast",function () {
                item.remove();

                _painter.repaintScroll();
            });
        }
    }
}

function MultiSelection() {
}
MultiSelection.prototype = {
    clearMultiSelection:function(){
        $(".icotop-span").removeClass("selected");
    },
    refreshSelectionUI:function () {
        var $lilist = _multiSelection.getLiSelection();
        this.refreshLiList($lilist);
    },
    refreshLiList:function ($lilist) {
        $lilist.each(function (idx,e) {
            var $li = $(e);
            var tp = $li.data("type");
            var id = $li.data("id");
            if(tp == "dir"){
                var one = _dataManager.getDirData(id);
                _painter.setDirModelDataToUiEle($li,one);
            }else {
                var one = _dataManager.getFileData(null,id);
                _painter.setFileModelDataToUiEle($li,one);
            }
        });
    },
    isMultiSelected:function () {
        return _multiSelection.getIconsSelection().length > 1;
    },
    getIconsSelection:function () {
        return $(".icotop-span.selected");
    },
    getLiSelection:function () {
        return this.getIconsSelection().parents("li");
    },
    getSelectionDataArr:function () {
       var arr = this.getLiSelection();
        var ret = [];
        arr.each(function (i, e) {
            var tp = $(e).data("type");
            var id = $(e).data("id");
            if(tp == "dir"){
                var one = _dataManager.getDirData(id);
                ret.push(one);
            }else {
                var one = _dataManager.getFileData(null,id);
                ret.push(one);
            }
        });
        return ret;
    },
    getSelectionDataArrWithType:function (withType) {
       var arr = this.getLiSelection();
        var ret = [];
        arr.each(function (i, e) {
            var tp = $(e).data("type");
            var id = $(e).data("id");

            if(tp == "dir"){
                var one = _dataManager.getDirData(id);
                ret.push(_multiSelection.cloneOneWithType(one,tp,withType));
            }else {
                var one = _dataManager.getFileData(null,id);
                ret.push(_multiSelection.cloneOneWithType(one,tp,withType));
            }
        });
        return ret;
    },
    cloneOneWithType:function (one,type,withType) {
        var ret = $.extend({},one);
        if(withType){
            ret.type = type;
        }
        return ret;
    },
    getSelectionGroupDataArr:function () {
       var arr = this.getLiSelection();
        var ret = {
            dirs:[],
            files:[]
        };

        arr.each(function (i, e) {
            var tp = $(e).data("type");
            var id = $(e).data("id");
            if(tp == "dir"){
                var one = _dataManager.getDirData(id);
                ret.dirs.push(one);
            }else {
                var one = _dataManager.getFileData(null,id);
                ret.files.push(one);
            }
        });
        return ret;
    },
    getCuttingGroupData:function () {
        return this.getGroupDataByProp("_cutting");
    },
    getGroupDataByProp:function (prop) {
        var ret = {
            dirs:[],
            files:[]
        };

        var arr1 = _dataManager.findDirData(prop,true);
        arr1.map(function (e) {
            ret.dirs.push(e);
        });

        var arr2 = _dataManager.findFileData(prop,true);
        arr2.map(function (e) {
            ret.files.push(e);
        });

        return ret;
    },
    updateLiSelectionUI:function (cls) {
        return this.getLiSelection().addClass(cls);
    },
    hasCut:function () {
        var l1 = _dataManager.findDirData("_cutting",true).length > 0;
        var l2 = _dataManager.findFileData("_cutting",true).length > 0;
        return l1 || l2;
    },
    hasCopying:function () {
        var l1 = _dataManager.findDirData("_copying",true).length > 0;
        var l2 = _dataManager.findFileData("_copying",true).length > 0;
        return l1 || l2;
    },
    hasCutorCopy:function () {
        return this.hasCut() || this.hasCopying();
    },
    clearAllObjectUIAndProp:function (clsName, prop, val) {
         $("li."+clsName).removeClass(clsName);

        var dirs = _dataManager.findDirData(prop, val);
        // console.log(dirs);
        var files = _dataManager.findFileData(prop, val);
        // console.log(files);

        dirs.map(function (e) {
            delete e[prop];
        });
        files.map(function (e) {
            delete e[prop];
        });

    },
    updateObjectProp:function ($li_list,cutPropName,cutPropVal) {
        $li_list.each(function (i,e) {
            _dataManager.processUpdateByLi($(e),cutPropName,cutPropVal);
        });
    }
}

function AlertManager() {
}
AlertManager.prototype = {
    alertBase:function (msg) {
        layer.confirm(msg, {
            title:' ',
            skin: 'layui-layer-zhs',
            icon:0,
            shade:.6,
            btn: [zLocale.public_confim] //按钮
        }, function(index,layero){
            layer.close(index) ;
        });
    },
    alertDirExists:function (dirName) {
        this.alertBase("The folder named “***” exists!");
    },
    alertDirPathIllegal:function () {
        this.alertBase(zLocale.database_paste_error_children);
    }
}

var _factory = new DivBuilder();//用来创建 文件，文件夹 div的工厂类
var _painter = new Painter();//用来控制文件及文件夹的绘制流程，将内容元素提交给PageHandler分页处理，展示
var _pageHandler= new PageHandler();//目前无分页功能，所以直接对内容元素数组全部展示
var _dirManager = new DirManager();//用来获取跟文件夹有关的数据，如当前在哪个文件夹，某个文件夹的数据，某个文件夹的子文件夹id数组
var _fileManager = new FileManager();//只有一个文件过滤函数比较实用，只显示tabView文件类型的文件
var _dataManager = new DataManager();//本地缓存_data的crud类，比如新增一个文件需要调用该类方法函数添加到本地_data里，并且维护了关系
var _multiSelection= new MultiSelection();//判断多选情况的类，同时也可以获取当前哪些图标已被选中
var _alertManager= new AlertManager();//layer弹框的包装，美化版的alert

//获取课程下面所有文件夹数据，包含了层级结构，根文件夹id等等
//传入参数是个回调函数
function refreshDirData(cb) {
    $.ajax({
        url: basePath + "/course/thirdStep/dir/list",
        data: {"courseId": $("#courseId").val()},
        async: true,
        cache:false,
        success: function (json) {
//                console.log(json);
            if (isRequestSuccess(json)) {
                _data = json.result;
                _data.files=[];

                cb(json.result);
            }
        }
    });
}

//无用
// function refreshFileData(dirId,cb) {
//     $.ajax({
//         url: basePath + "/course/thirdStep/file/map",
//         data: {"foldIds": "" + dirId},
//         async: true,
//         cache:false,
//         success: function (json) {
// //                            console.log(json);
//             if (isRequestSuccess(json)) {
//                 _data.files = json.result.files;
//                 console.log(_data);
//
//                 cb(json.result.files);
//             }
//         }
//     });
// }

//重新绘制当前页，相当于刷新
//无用
// function clearAndRefreshCurrentPage() {
//     refreshDirData(function () {
//         _painter.paint(true);
//     });
// }

$(function () {
    //阻止图片预览的滚动
    //.layui-layer-shade,.layui-layer-page,.layui-layer-content
    $(document).delegate('.tm-ui-overdisplay,#tm-box-wrap','mousewheel DOMMouseScroll', function (e) {
        // console.log('aaa');
        e.preventDefault();
        e.stopPropagation();
    });

    //initial query-dir
    refreshDirData(function (dirData) {
        var rootDirId = dirData.rootDirId;
        var childrenDirIds = dirData.childrenDirIds;

        //query root dir files
        // refreshFileData(rootDirId,function (fileData) {
        //     _dirManager.enterDirectory(rootDirId);
        // });


        //query all dir files
        childrenDirIds.push(rootDirId);
        $.ajax({
            url: basePath + "/course/thirdStep/file/map",
            data: {"foldIds": "" + childrenDirIds.join(",")},
            async: true,
            cache:false,
            success: function (json) {
//                            console.log(json);
                if (isRequestSuccess(json)) {
                    _data.files = json.result.files;
                    console.log(_data);

                    _dirManager.enterDirectory(rootDirId);
                }
            }
        });

    });
    

    console.log('start bind events...');

    //禁止页面元素拖动
    document.ondragstart = function() {
        return false;
    };


    //bind events
    bindAllEvents();

    //bind contextmenu events
    bindContextMenuEvents();//listen document

    //bind contextmenu events
    bindUpload();

    //
    bindIconClick();//listen document

    // bindDelete();//已经没有删除图标了 只能通过右键

    bindLeftTab();

    bindRename();//listen document
    bindCreateFolder();

    bindPicPreview();

    console.log('end bind events...');

});

//粘贴到目标文件夹destDirId，会查找_data中存在prop属性的文件夹及文件数据，清除页面class包含propCls的元素的该样式
//XHR，更新本地_data
function pasteToDir(propCls,prop,destDirId) {
    //record
    var affectedArr = _multiSelection.getGroupDataByProp(prop);
    var destDirData = _dataManager.getDirData(destDirId);
    var postDirIds = $.cutArrayProp(affectedArr.dirs,"id");
    var postFileIds = $.cutArrayProp(affectedArr.files,"id");

    //concat param
    var postDirParam = {
        folderIds:postDirIds,
        parentId:destDirId
    };
    var postFileParam = {
        fileIds:postFileIds,
        folderId:destDirId
    };

    var newPri = _dataManager.getDirData(destDirId).privilege || 0;
    //权限缩小时才更新
    if(newPri == 1){
        postDirParam.privilege=1;
        postFileParam.privilege=1;
    }

    console.log('post param...');
    console.log(postDirParam);
    console.log(postFileParam);

    var successCb = function () {
        //refresh    ui and cache
        // clearAndRefreshCurrentPage();

        //不刷新版 更新js cache，js relation cache，update ui
        //update cache
        // _multiSelection.clearAllObjectUIAndProp("cutting","_cutting",true);
        // _multiSelection.clearAllObjectUIAndProp("copying","_copying",true);
        _multiSelection.clearAllObjectUIAndProp(propCls,prop,true);

        var affectedIncludingChildrenArr =  _dirManager.getAffectedChildrenDirFileBySelectionDataArr(affectedArr);

        console.log("affectedArr:");
        console.log(affectedArr);
        console.log("affectedIncludingChildrenArr:");
        console.log(affectedIncludingChildrenArr);

        //权限影响子目录
        if(newPri == 1){
            affectedIncludingChildrenArr.dirIds.map(function (id) {
                var dt = _dataManager.getDirData(id);
                dt.privilege = newPri;
            });

            affectedIncludingChildrenArr.fileIds.map(function (id) {
                var dt = _dataManager.getFileData(null,id);
                dt.privilege = newPri;
            });
        }


        //update data
        //只修改直接目录和文件  不修改子
        affectedArr.dirs.map(function (dt) {
            var oldParentDirId = dt.parentId;
            var destDirId = destDirData.id;
            //update cache
            dt.parentId = destDirId;

            //remove relationship
            var oldArr = _data.dirMapping[oldParentDirId] || [];
            oldArr.remove(dt.id);

            //push relationship
            if ( _data.dirMapping[destDirId] == undefined) {
                _data.dirMapping[destDirId] = [];
            }
            var destArr = _data.dirMapping[destDirId];
            destArr.push(dt.id);
        });

        affectedArr.files.map(function (dt) {
            var oldParentDirId = dt.folderId;
            var destDirId = destDirData.id;
            //update cache
            dt.folderId = destDirId;

            //remove relationship
            var oldArr = _data.files[oldParentDirId] || [];
            var tIdx = $.findOneIdxByProp(oldArr,"id",dt.id);
            if (tIdx >= 0 ) {
                oldArr.splice(tIdx,1);
            }

            //push relationship
            if ( _data.files[destDirId] != undefined) {
                var destArr = _data.files[destDirId];
                destArr.push(dt);
            }

        });

        //update ui
        if(destDirId == _dirManager.currentDirId()){
            affectedArr.dirs.map(function (dt) {
                var ex_li = _painter.getDirLiById(dt.id,true);
                if (!ex_li || ex_li.length==0) {
                    var $li = _painter.createChildrenDirOne(dt);
                    _pageHandler.processNewItem($li);
                }
            });
            affectedArr.files.map(function (dt) {
                var ex_li = _painter.getDirLiById(dt.id,false);
                if (!ex_li ||ex_li.length==0) {
                    var $li = _painter.createChildrenFileOne(dt);
                    _pageHandler.processNewItem($li);
                }
            });
        } else {
            affectedArr.dirs.map(function (dt) {
                var $li = _painter.getDirLiById(dt.id,true);

                _pageHandler.processDeleteItem($li);
            });
            affectedArr.files.map(function (dt) {
                var $li = _painter.getDirLiById(dt.id,false);
                _pageHandler.processDeleteItem($li);
            });
        }
    }

    successCb();

    //XHR change data in db
    if(postDirIds.length > 0){
        $.ajax({
            url: basePath + "/course/thirdStep/dir/updateMulti",
            data: postDirParam,
            type:"post",
            async: true,
            success: function (json) {
                if (isRequestSuccess(json)) {
                    json.result.map(function (dt) {
                        _painter.refreshDir(dt,"name");
                    })
                }
            }
        });
    }

    if(postFileIds.length > 0){
        $.ajax({
            url: basePath + "/course/thirdStep/file/updateMulti",
            data: postFileParam,
            type:"post",
            async: true,
            success: function (json) {
                if (isRequestSuccess(json)) {
                    json.result.map(function (dt) {
                        _painter.refreshFile(dt,"name");
                    })
                }
            }
        });
    }
}
//将当前选中项数据标记_moving，并添加moving样式
function setMovingData() {
    //clear cut object first
    //clear cut object in js data
    _multiSelection.clearAllObjectUIAndProp("moving","_moving",true);

    //update UI
    var $li_list = _multiSelection.updateLiSelectionUI("moving");

    //update js data
    _multiSelection.updateObjectProp($li_list,"_moving",true);
}

function bindPicPreview() {
    $.tmImgbox({
        src:_dataManager.getCurrentPictureData
    });
}

function bindCreateFolder() {
    //create a folder按钮
    $(".greatefolder-div").click(function (e) {
        e.stopPropagation();

        var $li = _painter.createChildrenDirOne({privilege:_dirManager.currentDirPri()});
        $li.data("new",true);
        _pageHandler.processNewItem($li,true);//需要instant 不然导致点击失效
        // console.log($li.find("p.editdataname-p"));
        setTimeout(function () {
            // console.log($li.find("p.editdataname-p"));
            $li.find("p.editdataname-p").click();
            // changeToInputStatus(  $li.find("p.editdataname-p"));
        },0);
    });
}

function bindLeftTab() {
    //左侧tab按钮
    $(".databasecontet-div .databasecontet-l").on("click", "li", function (e) {
        $(this).siblings().removeClass("cur");
        $(this).addClass("cur");
        var newTabIndx = parseInt($(this).attr("data-tabView"));
        var newDirIndx = parseInt($(this).attr("data-dirView"));
        _painter.changeTab(newTabIndx,newDirIndx);
    });
}

function bindDelete() {
    //删除
    $(getContentContainer()).on("click", ".deleteico", function (e) {
        deletePost($(this));
    });
}

//重命名逻辑
function bindRename() {
    //阻塞桌面失去焦点点击
    $(document).on("click", function (e) {
// //            console.log('document click');
//         if(!shouldBlockNameInput()){
            hideAllEditingName();
//         }
    });

    //切换成输入状态
    $(getContentContainer()).on("click", "p.editdataname-p", function (e) {
        changeToInputStatus( $(this),e);
    });

    //防止触发body click而失去焦点
    $(getContentContainer()).on("click", "div.editdataname-div > input", function (e) {
        e.stopPropagation();
    });

    //回车=确认
    $(getContentContainer()).on("keydown", "div.editdataname-div > input", function (e) {
//            console.log(e.which);
        if (e.which == 13) {
            e.preventDefault();

            // if (!shouldBlockNameInput()){
                $(this).blur();
                hideAllEditingName();
            // }
        }
    });

    var doUpdateFolderName = function ($li,prevVal,thisVal) {
        var id = $li.data("id");
        var tp = $li.data("type");

        //创建模式
        if(!id) {
            //
            if(isEmpty(thisVal)){
                thisVal = zLocale.database_newfoler;//TODO
            }

            console.log('create a folder first');

            //initial create-dir
            $.ajax({
                url: basePath + "/course/thirdStep/dir/create",
                type:"post",
                data: {
                    parentId:_dirManager.currentDirId(),
                    courseId:$("#courseId").val(),
                    name:thisVal,
                    privilege:_dirManager.currentDirPri()
                },
                async: true,
                success: function (json) {
                    if (isRequestSuccess(json)) {
                        var dirData = json.result;
                        console.log(dirData);

                        _painter.setDirModelDataToUiEle($li,dirData);
                        _dataManager.processNewDir(dirData);
                    }
                }
            });
            //end of create-dir
        }
        //更新模式
        else {
            console.log('update folder name');

            //
            if(isEmpty(thisVal)){
                return;//ignore empty update request
            }
            if (prevVal == thisVal) {
                return;
            }

            $.ajax({
                url: basePath + "/course/thirdStep/dir/update",
                data: {id:id,name:thisVal},
                type:"post",
                async: true,
                success: function (json) {
                    if (isRequestSuccess(json)) {
                        var dirData = json.result;
                        console.log(dirData);

                        _painter.refreshDir(dirData,"name");
                    }

                    // else {
                    //     _alertManager.alertDirExists(thisVal);
                    // }
                }
            });
        }
    }

    var doUpdateFileName = function ($li,prevVal,thisVal) {
        if(isEmpty(thisVal)){
            return;//ignore empty update request
        }
        if (prevVal == thisVal) {
            return;
        }

        var id = $li.data("id");
        var tp = $li.data("type");
        var suffix = _fileManager.getSuffix(_dataManager.getFileData(_dirManager.currentDirId(),id));
        var fullName=thisVal+"."+suffix;

//
        $.ajax({
            url: basePath + "/course/thirdStep/file/update",
            data: {id:id,name:fullName},
            type:"post",
            async: true,
            success: function (json) {
                if (isRequestSuccess(json)) {
                    var dirData = json.result;
                    console.log(dirData);

                    _painter.refreshFile(dirData,"name");
                }
            }
        });

    }


    //修改名称
    //失焦=请求
    $(getContentContainer()).on("blur", "div.editdataname-div > input", function (e) {
        e.stopPropagation();
        console.log("blur");

        var $next = $(this).parent("div.editdataname-div").next("p");
        var prevVal = $next.text();
        var thisVal = $.trim($(this).val());
        var $li = $(this).parents("li");
        var id = $li.data("id");
        var tp = $li.data("type");

        console.log("id:"+ id);
        console.log("type:"+ tp);
        console.log("prevVal:"+prevVal);
        console.log("thisVal:"+thisVal);


        if (tp=="dir"){
            doUpdateFolderName($li,prevVal,thisVal);
        } else {
            doUpdateFileName($li,prevVal,thisVal);
        }

    });
}

function bindUpload() {
    var param =getVideoUploadParam();
    param.allowSuffix=$.mapKeys(_meta.suffixToType).join("|");
    param.targetId="uploadFileBtnGen";
    console.log(param);

    setVideoUploadCallback(param);
    var $orgBtn = $("#uploadFileBtn");

    var generatedId="xyzUploadLvId"+new Date().getTime();
    var $newDiv = $("<div></div>");
    $newDiv.attr("id",generatedId);

    $orgBtn.append($newDiv);
    param.targetId=generatedId;
    // param.buttonWidth ="50";
    // param.buttonHeight ="50";// IE789下设置此按钮高度生效

    try {
        $orgBtn.Ableuploader(param);
    }catch (e){console.error(e)};
}


function getContentContainer() {
    return "#" + _meta.contentId;
}



function bindContextMenuEvents() {
    //为了更好的体验 禁止背景右键菜单
    $(document).on("contextmenu", function (e) {
        e.preventDefault();
    });


    context.init({
        preventDoubleContext: true,
        above:'auto',
        filter:function () {
            // console.log(arguments);
        },
        actionPostProcessor:function () {
            //取消选择
            // _multiSelection.clearMultiSelection();
        }
    });

    // context.settings({compress: true});
    for(var n in _meta.contextMenuMap) {
        var markClasses=splitBySpace(n);
        var items = _meta.contextMenuMap[n]["map"];
        var markClassesStr="."+markClasses.join(".");
        // console.log(markClassesStr);

        // if(items.length==0){
        //     $(document).on('contextmenu', markClassesStr, closeAllContextMenu);
        // }else {
        // console.log(markClassesStr);
        // console.log(items);
            context.attach(markClassesStr, items,_meta.contextMenuMap[n]["decorator"],_meta.contextMenuMap[n]["positionConfig"]);
        // }

    }

    //container contextmenu
    context.attach( '.databasecontet-r', _meta.contextMenuMap["mainContainer"]["map"],_meta.contextMenuMap["mainContainer"]["decorator"],_meta.contextMenuMap["mainContainer"]["positionConfig"]);
    // $(document).on('contextmenu', '#fileContent', closeAllContextMenu);


}

function changeToInputStatus($this,e) {
    //关闭所有右键菜单
    //因为阻止了冒泡 必须手动关闭菜单
    context.closeAll();

    if(e){
        e.stopPropagation();
    }
//            console.log('prev enter');
    if (shouldBlockNameInput()){
        return;
    }

    hideAllEditingName();

    var $prev = $this.prev("div.editdataname-div");
    var $input = $prev.children("input");
    $this.hide();
    console.log($prev);
    console.log($input);
    console.log($this);

    $input.val($this.text());
    $prev.show();
    $input.textFocus();
    $input.select();
}

function bindIconClick() {
    //取消多选


    var lastIconClick=null;
    var isMoving;
    var lastX;
    var lastY;
    var ghost;
    var _distance_threshold = 10;
    var _ghost_class = "dragGhost";

    //图标按下事件
    $(getContentContainer()).on("mousedown", ".icotop-span", function (e) {
        // e.stopPropagation();
        // console.log(e.button);
        // console.log(e.buttons);
        // console.log('图标mousedown1');

        //仅支持左键
        if(!isleftMouseDown(e)){
            return;
        }
        // console.log('图标mousedown2');
        //
        var isPrevDir = $(this).children().hasClass("prev");
        //不支持上一步文件夹

        if(isPrevDir){
            return;
        }

        //ctrlKey操作
        if(e.ctrlKey){
            $(this).toggleClass("selected");
            // e.stopPropagation();//不然会清除其它选择项
        } else {
            $(this).addClass("selected");
        }

        // console.log(e);

        lastIconClick = $(this);
        lastX = e.pageX;
        lastY = e.pageY;
    });

    $(document).on("mousemove", function (e) {
        // console.log(e);
        // 左键按住时
        // if(e.buttons > 0 ){
        //计算是否在移动
        if(!isMoving && lastIconClick != null){
            console.log(e.buttons);
            // console.log(e);
            var curX = e.pageX;
            var curY = e.pageY;
            var distanceGte = (Math.abs(curX-lastX)>=_distance_threshold)||(Math.abs(curY-lastY)>=_distance_threshold);

            isMoving = _multiSelection.getIconsSelection().length > 0 && distanceGte;//有选中,并且位移了一段距离算移动

            if(isMoving){
                ghost = $("<div><ul><li><div></div></li></ul></div>");
                ghost.addClass(_ghost_class);
                ghost.addClass("databasecontet-r");
                ghost.find("div").addClass("databasecontetdiv");


                // ghost = lastIconClick.clone();

                ghost.find("div").append(lastIconClick.clone());
                ghost.find(".selected").removeClass("selected");

                ghost.css({
                    "opacity":"0.5",
                    "filter":"alpha(opacity=50)",
                    "position":"absolute",
                    "z-index":"99999",
                });

                ghost.css({
                    "width":"108px",
                    "height":"108px",
                });


                $("body").append(ghost);
            }
        }

        if(_navig.ie){
            //移除ie下的选择效果
            try {
                if (document.selection) {
                    // Timeout neccessary for IE9
                    // setTimeout(function () {
                    document.selection.empty();
                    // });
                } else {
                    window.getSelection().removeAllRanges();
                }
            } catch (err) {
            }
        }

        if(isMoving){
            // ghost.animate({"left":e.pageX+20,"top":e.pageY+20});
            ghost.css({"left":e.pageX+1,"top":e.pageY+1});

            $(".movingSelected").removeClass("movingSelected");
            $(e.target).closest(".icotop-span").addClass("movingSelected");
        }
    });

    $(document).on("click", function (e) {
        //非ctrlKey操作时清除
        if(!e.ctrlKey){
            //清除其它
            if(!$(e.target).closest(".icotop-span").hasClass("selected")){
                // console.log('clearMultiSelection call');
                _multiSelection.clearMultiSelection();
            }
        }

    });


    $(document).on("mouseup", function (e) {
        if(isMoving) {
            _multiSelection.clearMultiSelection();
        }

        isMoving = false;
        lastIconClick = null;

        $("."+_ghost_class).remove();
        $(".movingSelected").removeClass("movingSelected");
    });

    //图标松开事件
    $(getContentContainer()).on("mouseup", ".icotop-span", function (e) {
        // e.stopPropagation();
        //仅支持左键
        if(!isleftMouseDown(e)){
            return;
        }

        //关闭所有右键菜单
        //因为阻止了冒泡 必须手动关闭菜单
        context.closeAll();

        var tempTp = $(this).parents("li").data("type");
        console.log(tempTp);
        var tempId = $(this).parents("li").data("id");
        console.log(tempId);
        console.log(_dataManager.findFileData("id",tempId));
        console.log(_dataManager.findDirData("id",tempId));


        var isCommonDir = !!$(this).find("> .file.common").length;
        var isPrevDir = !!$(this).find("> .file.prev").length;
        var isSelected = $(this).hasClass("selected");
        var isDeleteClick = $(e.target).hasClass("deleteico");
        //没有按住ctrl键时
        if(!e.ctrlKey ){

            //若处于移动中，判定为非点击事件
            if(!isMoving){
                _multiSelection.clearMultiSelection();

                if(isDeleteClick){
                    console.log('deleteico  ignore');
                    return;
                }

                if(isCommonDir){
                    console.log('common enter');
                    var dirId = $(this).parents("li").data("id");
                    console.log(dirId);
                    if (dirId) {
                        _dirManager.enterDirectory(dirId);
                    }
                    return;
                }

                if(isPrevDir){
                    console.log('prev enter');

                    _dirManager.popDirectory();
                    return;
                }



                if(_meta.iconAction[tempTp]){
                    var dt = _dataManager.getFileData(null, tempId);
                    _meta.iconAction[tempTp](tempId,dt,$(this).parents("li"));
                }
            } else {
                if($(this).hasClass("selected")){
                    return;
                }

                //此时代表移动到某个文件夹中
                //获取当前选中项
                setMovingData();
                var destDirId ;
                if(isCommonDir){
                    console.log('drop to common dir');
                    destDirId = $(this).parents("li").data("id");
                }

                if(isPrevDir){
                    console.log('drop to  prev ');
                    destDirId = _meta.currentPathArr[_meta.currentPathArr.length - 2];
                }

                if(destDirId){
                    console.log(destDirId);

                    pasteToDir("moving","_moving",destDirId);
                }
            }

        }
        //按住ctrl键时
        else if(e.ctrlKey && _config.isCtrlMultiSelectionEnabled){

        }


    });
}
function bindAllEvents() {
    console.log();
}

//多个选中项删除逻辑
function deleteMultiPost($lilist) {
    var newDirCount = 0;
    var total = $lilist.length;
    if (total <=0) {
        console.log('must select one first');
        return;
    }

    var dirIds = [];
    var fileIds = [];
    var tpCate = {};//各种type计数
    $lilist.each(function (idx, e) {
        var $li = $(e)
        var id = $li.data("id");
        var isNew = !id;
        var tp = $li.data("type");

        if(tp=="dir" && isNew){
            newDirCount++;
        }

        if(tp=="dir" && id){
            // var deletedDirIds = _dirManager.getThisAndAllChildrenDirIds(id);
            // _painter.pushToArr(dirIds, deletedDirIds);
            _painter.pushToArr(dirIds, id);
        }

        //file
        if(tp!="dir" && id){
            _painter.pushToArr(fileIds, id);
        }

        if(tpCate[tp] == undefined){
            tpCate[tp] = 0;
        }
        tpCate[tp]++;
    });

    if(newDirCount == total) {
        $lilist.each(function (idx, e) {
            var $li = $(e);
            _pageHandler.processDeleteItem($li);
        });
    } else {
        //confirm

        console.log(dirIds);
        console.log(fileIds);


        var r_title = total>1?zLocale.database_shanchutishis:zLocale.database_shanchutishi;
        console.log(r_title);

        //否则弹窗
        layer.confirm(r_title, {
            title: ' ',
            skin: 'layui-layer-zhs',
            icon: 0,
            shade: .6,
            btn: [zLocale.public_confim, zLocale.public_cancel] //按钮
        }, function (index, layero) {
            console.log("delete request");

            $lilist.each(function (idx, e) {
                _pageHandler.processDeleteItem($(e));
            });

            dirIds.map(function (idOne) {
                _dataManager.processRemoveDir(idOne);
            });
            fileIds.map(function (idOne) {
                _dataManager.processRemoveFile(idOne);
            });

            if(dirIds.length > 0) {
                $.ajax({
                    url: basePath + "/course/thirdStep/dir/delete",
                    data: {folderIds:dirIds},
                    type:"post",
                    async: true,
                    success: function (json) {
                        if (isRequestSuccess(json)) {
                            var dirData = json.result;
                            console.log(dirData);

                        }
                    }
                });

            }

            if(fileIds.length > 0) {
                $.ajax({
                    url: basePath + "/course/thirdStep/file/delete",
                    data: {fileIds:fileIds},
                    type:"post",
                    async: true,
                    success: function (json) {
                        if (isRequestSuccess(json)) {
                            var dirData = json.result;
                            console.log(dirData);

                            if(tpCate['video']){
                                console.log('refresh opener ... _opener_refresh_list');
                                _opener_refresh_list();
                            }
                        }
                    }
                });
            }

            layer.close(index);
        });
    }
}

//删除单个逻辑
function deletePost($this) {
    // var $this = $(this);
    var $li = $this.parents("li");
    var id = $li.data("id");
    var isNew = !id;
    var tp = $li.data("type");

    if(tp=="dir" && isNew){
        //新的目录直接删除
        _pageHandler.processDeleteItem($li);
        return;
    }

    //否则弹窗
    layer.confirm(zLocale.database_shanchutishi, {
        title: ' ',
        skin: 'layui-layer-zhs',
        icon: 0,
        shade: .6,
        btn: [zLocale.public_confim, zLocale.public_cancel] //按钮
    }, function (index, layero) {
        console.log("delete request");

        console.log("id:"+ id);
        console.log("type:"+tp);

        if(tp=="dir") {
            var deletedDirIds = _dirManager.getThisAndAllChildrenDirIds(id);
            console.log("deletedDirIds:"+ deletedDirIds);

            $.ajax({
                url: basePath + "/course/thirdStep/dir/delete",
                data: {folderIds:deletedDirIds},
                type:"post",
                async: true,
                success: function (json) {
                    if (isRequestSuccess(json)) {
                        var dirData = json.result;
                        console.log(dirData);

                        _pageHandler.processDeleteItem($li);

                        _dataManager.processRemoveDir(id);
                    }
                }
            });

        } else {
            console.log("deletedFileId:"+ id);

            $.ajax({
                url: basePath + "/course/thirdStep/file/delete",
                data: {fileId:id},
                type:"post",
                async: true,
                success: function (json) {
                    if (isRequestSuccess(json)) {
                        var dirData = json.result;
                        console.log(dirData);

                        _pageHandler.processDeleteItem($li);

                        _dataManager.processRemoveFile(id);

                        console.log(tp);
                        if(tp=='video'){
                            _opener_refresh_list();
                        }

                    }
                }
            });
        }

        layer.close(index);
    });
}


var closeAllContextMenu = function (e) {
    if(e){
        e.preventDefault();
    }
    context.closeAll();
}

function hideAllEditingName() {
    $("div.editdataname-div").hide();
    $("p.editdataname-p").show();
}

function shouldBlockNameInput() {
    return isNewFolderNameEmpty() || !_fileManager._last_unique_check || !_dirManager._last_unique_check;
}

function isNewFolderNameEmpty() {
    var liArr = $("div.editdataname-div:visible").parents("li");
    for (var i = 0; i < liArr.length; i++) {
        var obj = liArr.eq(i);

        if (!obj.data("id")) {
            var v = obj.find("input").val();
            if (isEmpty($.trim(v))){
                obj.find("input").focus();
                return true;
            }
        }
    }
    return false;
}

